package com.example.bustest;

import java.net.URL;
import java.net.URLEncoder;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

 public class MainActivity extends Activity implements OnClickListener {
	 
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 setContentView(R.layout.main);
		 
		 Button btn = (Button)findViewById(R.id.button1);
		 btn.setOnClickListener(this);
		 
	 }
	 
	 public void onClick(View v) {
		 
		 EditText editText1 = (EditText)findViewById(R.id.editText1);
		 
		 try {
			 String serviceUrl = "http://ws.bus.go.kr/api/rest/busRouteInfo/getBusRouteList";
			 String serviceKey = "OKJLjAtvWjTEGvHi7Iyzmx7LhXqLrGQaGdnVV75FkZ4ZiRNrOAw61cW5sayWE9Q3xFt989joOdoGI/30Ousbtw=="; // OpenAPI Key
             serviceKey = URLEncoder.encode(serviceKey);
             String strSrch = "505";
             String strURL = serviceUrl + "?ServiceKey=" + serviceKey + "&strSrch=" + strSrch;
             
             URL url = new URL(strURL);
             
             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
             XmlPullParser parser = factory.newPullParser();
             parser.setInput(url.openStream(), "utf-8");
             
             int eventType = parser.getEventType();
             
             boolean bSet = false;
             
             while (eventType != XmlPullParser.END_DOCUMENT) {
            	 switch (eventType) {
            	    case XmlPullParser.START_DOCUMENT:
            	    	break;
            	    	
            	    case XmlPullParser.START_TAG:
            	    	String tag = parser.getName();
            	    	if (tag.equals("busRouteNm") || tag.equals("stStationNm") || tag.equals("edStationNm")) {
            	    		bSet = true;
            	    	}
            	    	break;
            	    	
            	    case XmlPullParser.END_TAG:
            	    	break;
            	    	
            	    case XmlPullParser.TEXT:
            	    	if (bSet) {
            	    		String content = parser.getText();
            	    		editText1.append(content + "\n");
            	    		bSet = false;
            	    	}
            	    	break;
            	    	
            	    case XmlPullParser.END_DOCUMENT:
            	    	break;
            	 }
            	 
            	 eventType = parser.next();
             }
		 } catch (Exception e) {
			 Toast.makeText(v.getContext(), e.getMessage(), 0).show();
		 }
	 }
 }

  